package com.estore.action;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.interceptor.ServletRequestAware;

import com.estore.converter.DateTime;
import com.estore.converter.ImageResize;
import com.estore.converter.MD5;
import com.estore.entity.Account;
import com.estore.info.ProfileInfo;
import com.estore.manager.ProfileManager;
import com.estore.model.ProfileModel;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

public class ProfileAction extends ActionSupport implements
		ModelDriven<ProfileModel>, ServletRequestAware {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1305043957158350754L;
	ProfileModel profileModel = new ProfileModel();
	ProfileManager profileManager;
	DateTime dateTime = new DateTime();
	public HttpServletRequest request;
	private String productID;

	// change pwd by user
	public String changePwd() {
		boolean check = true;
		profileModel.setErrorChangeProfile(null);
		Map<String, Object> session = ActionContext.getContext().getSession();
		if (session.get("isBanned") == null
				|| session.get("isBanned").equals(0)) {

			profileModel.setErrorChangeProfile(null);
			if (session.get("role") == null) {
				return "login";
			} else {
				if (profileModel.getProfileInfo() != null) {
					ProfileInfo info = profileModel.getProfileInfo();
					String account = session.get("username").toString();
					String pwd = session.get("password").toString();
					info.setAccount(account);

					if (info.getPassword() == null
							|| info.getSecretAnswer() == null
							|| profileModel.getPassword().equals("")) {

						check = false;
					}
					if (profileManager.checkSecret(info)) {
						if (check == true) {
							if (MD5.encryptMD5(info.getPassword()).equals(pwd)) {
								profileManager.changePwd(info.getAccount(), MD5.encryptMD5(profileModel.getPassword()));

								session.remove("password");
								session.put("password", MD5.encryptMD5(profileModel.getPassword()));
								profileModel.setProfileInfo(null);
								profileModel.setErrorChangeProfile("Đổi Mật Khẩu thành công");
							} else {
								profileModel.setProfileInfo(null);
								profileModel.setErrorChangeProfile("Mật Khẩu hiện tại không đúng");
							}
						} else {
							profileModel.setErrorChangeProfile("Xin vui lòng điền đầy đủ thông tin");
							profileModel.setProfileInfo(null);
						}
					} else {
						profileModel.setErrorChangeProfile("Câu hỏi và câu trả lời bí mật không đúng");
						profileModel.setProfileInfo(null);
					}
				}
				return SUCCESS;
			}
		} else {
			return "banned";
		}
	}

	// change Email by user
	public String changeEmail() {
		boolean check = true;
		profileModel.setErrorChangeProfile(null);
		Map<String, Object> session = ActionContext.getContext().getSession();
		if (session.get("isBanned") == null || session.get("isBanned").equals(0)) {

			profileModel.setErrorChangeProfile(null);
			if (session.get("role") == null) {
				return "login";
			} else {
				if (profileModel.getProfileInfo() != null) {
					ProfileInfo info = profileModel.getProfileInfo();
					String account = session.get("username").toString();
					String userID = session.get("userID").toString();
					info.setAccount(account);
					if (info.getEmail() == null || info.getSecretAnswer() == null) {

						check = false;
					}
					if (profileManager.checkEmailAvail(info.getEmail())
							&& !(info.getEmail().equals(session.get("email").toString()))) {
						check = false;
						profileModel.setErrorChangeProfile("Email đã được sử dụng");
					}
					if (profileManager.checkSecret(info)) {
						if (check == true) {
							profileManager.changeEmail(info.getEmail(), userID);
							session.remove("email");
							session.put("email", info.getEmail());
							profileModel.setProfileInfo(null);
							profileModel.setErrorChangeProfile("Đổi Email thành công");
						} else {
							if (profileModel.getErrorChangeProfile().equals("")) {
								profileModel.setErrorChangeProfile("Xin vui lòng điền đầy đủ thông tin");
							}
							profileModel.setProfileInfo(null);
						}
					} else {
						profileModel.setErrorChangeProfile("Câu hỏi và câu trả lời bí mật không đúng");
						profileModel.setProfileInfo(null);
					}
				}
				return SUCCESS;
			}
		} else {
			return "banned";
		}
	}

	// add/ update avatar by user
	public String updateAvatar() {
		Map<String, Object> session = ActionContext.getContext().getSession();
		if (session.get("isBanned") == null || session.get("isBanned").equals(0)) {

			profileModel.setErrorChangeAvatar(null);
			if (session.get("role") == null) {
				return "login";
			} else {
				List<String> listFileName = new ArrayList<String>();
				List<File> fileUpload = profileModel.getImgUpload();
				String fileName = "";
				List<String> fileUploadName = profileModel.getImgUploadFileName();
				if (fileUpload != null) {
					for (int i = 0; i < fileUpload.size(); i++) {
						fileName = dateTime.addImgDate() + fileUploadName.get(i);
						String contextPath = request.getRealPath("/");
						String path = contextPath + "img/avatar/" + fileName;
						listFileName.add("img/avatar/" + fileName);
						try {
							File f = new File(path);
							BufferedImage originalImage = ImageIO.read(fileUpload.get(i));
							int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType();
							BufferedImage resizeImage = ImageResize.resizeImage(originalImage, type);
							ImageIO.write(resizeImage, "jpg", f);
							// FileUtils.copyFile(fileUpload.get(i), f);
						} catch (IOException e) {
							System.out.println(e.getMessage());
						}
						String linkAvatar = "";
						for (String record : listFileName) {
							linkAvatar = record;
						}
						String userID = session.get("userID").toString();
						profileManager.changeAvatar(linkAvatar, userID);
						session.remove("avatar");
						session.put("avatar", linkAvatar);
						profileModel.setImgUpload(null);
						profileModel.setImgUploadFileName(null);
					}
				} else {
					profileModel.setErrorChangeAvatar("Bạn chưa chọn ảnh");
				}
				return SUCCESS;
			}
		} else {
			return "banned";
		}
	}

	// change profile by user

	public String changeProfile() {
		profileModel.setErrorChangeProfile("");
		Map<String, Object> session = ActionContext.getContext().getSession();
		if (session.get("isBanned") == null || session.get("isBanned").equals(0)) {

			profileModel.setErrorChangeProfile(null);
			if (session.get("role") == null) {
				return "login";
			} else {
				boolean check = true;
				if (profileModel.getProfileInfo() != null) {
					ProfileInfo info = profileModel.getProfileInfo();
					if (info.getFirstName().equals("") || info.getLastName().equals("")
							|| profileModel.getDay().equals("-1") || profileModel.getMonth().equals("-1")
							|| profileModel.getYear().equals("-1")) {
						check = false;
					}
					if (check == true) {
						Integer year = Integer.parseInt(profileModel.getYear()) - 1900;
						String getDate = dateTime.getDate(year, Integer.parseInt(profileModel.getMonth()),
								Integer.parseInt(profileModel.getDay()));
						info.setDateOfBirth(getDate);
						String userID = session.get("userID").toString();
						info.setUserID(Integer.parseInt(userID));
						if (Integer.parseInt(profileModel.getSex()) == -1) {
							info.setSex("male");
						} else {
							info.setSex("female");
						}
						profileManager.changeProfile(info);
						session.put("firstName", info.getFirstName());
						session.put("lastName", info.getLastName());
						session.put("birthDay", info.getDateOfBirth());
						session.put("address", info.getAddress());
						session.put("gentle", info.getSex());
						profileModel.setProfileInfo(null);
						profileModel.setErrorChangeProfile("Đổi thông tin cá nhân thành công");
					} else {
						profileModel.setErrorChangeProfile("Xin vui lòng kiểm tra lại thông tin");
						profileModel.setProfileInfo(null);
					}
				}
				return SUCCESS;
			}
		} else {
			return "banned";
		}
	}

	// check email , secretQuestion, secretAnswer if match -> change pwd

	public String forgetPwd() {
		ProfileInfo info = profileModel.getProfileInfo();
		if (profileManager.checkForgetPwd(info)) {
			if (info.getPassword() != null) {
				String password = MD5.encryptMD5(info.getPassword());
				profileManager.changePwd(info.getAccount(), password);
				profileModel.setErrorForgetPwd(null);
			}
			return SUCCESS;
		} else {
			profileModel
					.setErrorForgetPwd("Thông tin không đúng, vui lòng nhập lại !!!!");
			profileModel.setProfileInfo(null);
			return ERROR;
		}
	}

	// update role
	public String updateRole() {
		Map<String, Object> session = ActionContext.getContext().getSession();
		if (session.get("isBanned") == null || session.get("isBanned").equals(0)) {

			if (session.get("role") == null) {
				return "login";
			} else if (session.get("role").equals(1) || session.get("role").equals(3)) {
				if (profileModel.getUserID() != null) {
					profileManager.updateRole(profileModel.getUserID());
				}
				return SUCCESS;
			} else {
				return ERROR;
			}
		} else {
			return "banned";
		}
	}

	// edit UserProfile
	public String editProfile() {
		Map<String, Object> session = ActionContext.getContext().getSession();
		if (session.get("isBanned") == null || session.get("isBanned").equals(0)) {

			if (session.get("role") == null) {
				return "login";
			} else if (session.get("role").equals(1)
					|| session.get("role").equals(3)) {
				profileManager.editProfileInfo(profileModel.getUserID(), profileModel.getLastName(),
						profileModel.getFirstName(), profileModel.getEmail(), profileModel.getDateOfBirth(), 
						profileModel.getSex(), profileModel.getAddress(), profileModel.getPhoneNumber());
				return "success";
			} else {
				return ERROR;
			}
		} else {
			return "banned";
		}
	}

	// show Profile
	public String showProfileByID() {
		Map<String, Object> session = ActionContext.getContext().getSession();
		if (session.get("isBanned") == null || session.get("isBanned").equals(0)) {

			if (session.get("role") == null) {
				return "login";
			} else if (session.get("role").equals(1) || session.get("role").equals(3)) {
				ProfileInfo info = profileManager.getProfileInfo(profileModel.getUserID());
				Account account = profileManager.getAccountInfo(profileModel.getUserID());
				if (info != null) {
					profileModel.setProfileInfo(info);
					profileModel.setFirstName(info.getFirstName());
					profileModel.setLastName(info.getLastName());
					profileModel.setEmail(info.getEmail());
					profileModel.setDateOfBirth(info.getDateOfBirth());
					profileModel.setSex(info.getSex());
					profileModel.setAddress(info.getAddress());
					profileModel.setPhoneNumber(info.getPhoneNumber());
					profileModel.setAccount(account.getAccount());
				}
				return SUCCESS;
			} else {
				return ERROR;
			}
		} else {
			return "banned";
		}
	}

	// list all profile
	public String listAllProfile() {
		Map<String, Object> session = ActionContext.getContext().getSession();
		if (session.get("isBanned") == null || session.get("isBanned").equals(0)) {

			if (session.get("role") == null) {
				return "login";
			} else if (session.get("role").equals(1) || session.get("role").equals(3)) {
				List<ProfileInfo> listprofileinfo = profileManager.getListProfileInfo();
				if (listprofileinfo != null) {
					profileModel.setListprofileinfo(listprofileinfo);
				}
				return "success";
			} else {
				return ERROR;
			}
		} else {
			return "banned";
		}
	}

	@Override
	public ProfileModel getModel() {
		return profileModel;
	}

	public ProfileModel getProfileModel() {
		return profileModel;
	}

	public void setProfileModel(ProfileModel profileModel) {
		this.profileModel = profileModel;
	}

	public ProfileManager getProfileManager() {
		return profileManager;
	}

	public void setProfileManager(ProfileManager profileManager) {
		this.profileManager = profileManager;
	}

	public static long getSerialversionuid() {
		return serialVersionUID;
	}

	public DateTime getDateTime() {
		return dateTime;
	}

	public void setDateTime(DateTime dateTime) {
		this.dateTime = dateTime;
	}

	public HttpServletRequest getRequest() {
		return request;
	}

	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}

	@Override
	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}

	public String getProductID() {
		return productID;
	}

	public void setProductID(String productID) {
		this.productID = productID;
	}
}
